package com.awspaass.user.apps.syncwechataddress;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.actionsoft.bpms.commons.database.ColumnMapRowMapper;
import com.actionsoft.bpms.org.model.UserModel;
import com.actionsoft.bpms.schedule.IJob;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.ORGAPI;
import com.awspaas.user.apps.shhtaerospaceindustrial.util.CoreUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class EventHelperTool implements IJob {

	public List<Department> getAllDeps(String companyId) {
		List<Department> depAll = new ArrayList<Department>();
		List<Map<String, Object>> departlist = null;

		try {
			String sql = "select * from BO_INFO_WECHAT_AWS where COMPANYIDAWS ='" + companyId + "'";
			departlist = DBSql.query(sql, new ColumnMapRowMapper(), new Object[] {});
			if (departlist.isEmpty() || departlist == null) {
				System.out.println("NO COMPANY");
				return null;
			}
			for (int i = 0; i < departlist.size(); i++) {
				Map<String, Object> dep = departlist.get(i);
				String name = CoreUtil.objToStr(dep.get("NAME"));
				String depidaws = CoreUtil.objToStr(dep.get("DEPIDAWS"));
				String idwechat = CoreUtil.objToStr(dep.get("IDWECHAT"));
				String parentidwechat = CoreUtil.objToStr(dep.get("PARENTIDWECHAT"));
				String companyidaws = CoreUtil.objToStr(dep.get("COMPANYIDAWS"));
				String companyidwechat = CoreUtil.objToStr(dep.get("CONMPANYIDWECHAT"));
				String parentidaws = CoreUtil.objToStr(dep.get("PARENTIDAWS"));
				Department d = new Department();
				d.setName(name);
				d.setDepidaws(depidaws);
				d.setIdwechat(idwechat);
				d.setParentidwechat(parentidwechat);
				d.setCompanyidaws(companyidaws);
				d.setCompanyidwechat(companyidwechat);
				d.setParentidaws(parentidaws);
				depAll.add(d);
			}

		} catch (Exception e) {
			e.printStackTrace();

		}

		return depAll;
	}

	public String getDepIdAwsByidwechat(String id_wechat, String companyid) {
		String depid = null;
		List<Map<String, Object>> departlist = null;
		try {
			String sql = "select * from BO_INFO_WECHAT_AWS where COMPANYIDAWS='" + companyid + "' and IDWECHAT = '"
					+ id_wechat + "'";
			departlist = DBSql.query(sql, new ColumnMapRowMapper(), new Object[] {});
			if (departlist.isEmpty() || departlist == null) {
				System.out.println("NO DEPARTMENT");
				return null;
			}
			Map<String, Object> dep = departlist.get(0);
			depid = CoreUtil.objToStr(dep.get("DEPIDAWS"));
		} catch (Exception e) {
			e.printStackTrace();

		}
		return depid;
	}

	public void UpdateDepartments(List<Map<String, String>> dep_wechat, List<Department> dep_aws, String companyid_aws,
			String companyid_wechat) {

		/*
		 * System.out.println("微信部门数目："+dep_wechat.size()/3+" ，aws部门数目"+dep_aws.size());
		 * if(dep_wechat.size()/3<=dep_aws.size()) { return; }
		 */

		for (int i = 0; i < dep_wechat.size(); i++) {
			String id_wechat = dep_wechat.get(i).get("id");
			i++;
			String name_wechat = dep_wechat.get(i).get("name");
			i++;
			String parentid_wechat = dep_wechat.get(i).get("parentid");
			int j = 0;
			// System.out.println("微信部门ID:"+id_wechat);
			// System.out.println("微信部门名称："+name_wechat);
			// System.out.println("parentid_wechat"+parentid_wechat);
			String depQuerySql = "select * from BO_INFO_WECHAT_AWS t where t.conmpanyidwechat =  '" + companyid_wechat
					+ "'and t.idwechat = '" + id_wechat + "'";
			List<Map<String, Object>> depQueryList = DBSql.query(depQuerySql, new ColumnMapRowMapper(),
					new Object[] {});

			if (depQueryList == null) {
				System.out.println("depQuerySql Error!");
				return;
			}

			if (depQueryList.size() == 0) {
				String newDepId;
				String dep_p_id_aws = getDepIdAwsByidwechat(parentid_wechat, companyid_aws);
				if (("0").equals(parentid_wechat)) {
					newDepId = SDK.getORGAPI().createDepartment(companyid_aws, name_wechat, null, null, "0", null,
							null);
				} else {
					newDepId = SDK.getORGAPI().createDepartment(companyid_aws, name_wechat, null, null, dep_p_id_aws,
							null, null);
				}
				System.out.println("Insert" + name_wechat);
				String sql = "INSERT INTO BO_INFO_WECHAT_AWS  (DEPIDAWS,IDWECHAT,PARENTIDWECHAT,NAME,COMPANYIDAWS,CONMPANYIDWECHAT,PARENTIDAWS)VALUES(:DEPIDAWS,:IDWECHAT,:PARENTIDWECHAT,:NAME,:COMPANYIDAWS,:CONMPANYIDWECHAT,:PARENTIDAWS)";
				Map<String, Object> paraMap = new HashMap<>();
				paraMap.put("DEPIDAWS", newDepId);
				paraMap.put("IDWECHAT", id_wechat);
				paraMap.put("PARENTIDWECHAT", parentid_wechat);
				paraMap.put("NAME", name_wechat);
				paraMap.put("COMPANYIDAWS", companyid_aws);
				paraMap.put("CONMPANYIDWECHAT", companyid_wechat);
				paraMap.put("PARENTIDAWS", dep_p_id_aws);
				DBSql.update(sql, paraMap);
			} else {
				Map<String, Object> dep = depQueryList.get(0);
				String dep_name_aws = CoreUtil.objToStr(dep.get("NAME"));
				String depidAws = CoreUtil.objToStr(dep.get("DEPIDAWS"));

				if (dep_name_aws.equals(name_wechat)) {
					continue;
				} else {
					// System.out.println("update BO_INFO_WECHAT_AWS t set t.name='"+ name_wechat+"'
					// where t.companyidaws= '"+companyid_aws + "' and t.idwechat='" + id_wechat+
					// "'");
					DBSql.update("update BO_INFO_WECHAT_AWS t set t.name='" + name_wechat + "' where t.companyidaws= '"
							+ companyid_aws + "' and t.idwechat='" + id_wechat + "'");
					SDK.getORGAPI().updateDepartment(depidAws, name_wechat, ORGAPI.NO_UPDATE, ORGAPI.NO_UPDATE,
							ORGAPI.NO_UPDATE, ORGAPI.NO_UPDATE);

				}
			}
			/*
			 * for(j =0; j<dep_aws.size();j++) {
			 * if(name_wechat.equals(dep_aws.get(j).getName())) break; }
			 * if(j>=dep_aws.size()) { //System.out.println("Need to crete "+name_wechat);
			 * 
			 * 
			 * 
			 * }
			 */
		}
	}

	public List<UserModel> getAllUserByDepartments(List<Department> departments) {
		if (departments.size() == 0)
			return null;
		List<UserModel> employees = null;
		for (int i = 0; i < departments.size(); i++) {
			List<UserModel> e = SDK.getORGAPI().getAllUsersByDepartment(departments.get(i).getDepidaws());
			if (employees == null)
				employees = e;
			else
				employees.addAll(e);

		}
		return employees;
	}

	public String readToString(String fileName) {
		String encoding = "UTF-8";
		File file = new File(fileName);
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		try {
			FileInputStream in = new FileInputStream(file);
			in.read(filecontent);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return new String(filecontent, encoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println("The OS does not support " + encoding);
			e.printStackTrace();
			return null;
		}
	}

	public void updateExt5(List<Department> depAws, List<WxUserInfo> wechatuserlist) {

		List<UserModel> employees = getAllUserByDepartments(depAws);
		for (WxUserInfo userWechat : wechatuserlist) {

		}
		for (UserModel userAws : employees) {

		}

		// SDK.getORGAPI().updateUser(uid, ORGAPI.NO_UPDATE, ORGAPI.NO_UPDATE,
		// ORGAPI.NO_UPDATE, ORGAPI.NO_UPDATE, ORGAPI.NO_UPDATE, ORGAPI.NO_UPDATE,
		// ORGAPI.NO_UPDATE, ORGAPI.NO_UPDATE, java.lang.String ext5)

	}

	public void updateUserTable(List<WxUserInfo> wechatUserList, String companywechatid) {
		for (WxUserInfo user : wechatUserList) {
			String userId = user.getUserId();
			String depId = user.getDepartmentId();
			String userName = user.getName();
			String mobile = user.getMobile();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Date now = new Date(System.currentTimeMillis());
			String updateDate = formatter.format(now);
			String queryUserSql = "SELECT * from WECHAT_USER WHERE USERID='" + userId + "'";
			String updateUserSql = "UPDATE WECHAT_USER SET DEPID = '" + depId + "' ,USERNAME='" + userName
					+ "',COMPANYID='" + companywechatid + "', MOBILE='" + mobile + "',STATUS='0' WHERE USERID='"
					+ userId + "'";
			List<Map<String, Object>> userWechatList = DBSql.query(queryUserSql, new ColumnMapRowMapper(),
					new Object[] {});
			if (userWechatList.size() > 0) {
				Map<String, Object> userWechat = userWechatList.get(0);
				String userIdWechat = CoreUtil.objToStr(userWechat.get("USERID"));
				String depIdWechat = CoreUtil.objToStr(userWechat.get("DEPID"));
				String userNameWechat = CoreUtil.objToStr(userWechat.get("USERNAME"));
				String MOBILE = CoreUtil.objToStr(userWechat.get("MOBILE"));
				if (!userIdWechat.equals(userId) || !depIdWechat.equals(depId) || !userNameWechat.equals(userName)
						|| !MOBILE.equals(mobile)) {
					DBSql.update(updateUserSql);
				}
			} else {
				String insertUserSql = "INSERT INTO WECHAT_USER(USERID,DEPID,USERNAME,MOBILE,STATUS,COMPANYID)VALUES(:USERID,:DEPID,:USERNAME,:MOBILE,:STATUS,:COMPANYID)";
				Map<String, Object> paraMap = new HashMap<>();
				paraMap.put("USERID", userId);
				paraMap.put("DEPID", depId);
				paraMap.put("USERNAME", userName);
				paraMap.put("MOBILE", mobile);
				paraMap.put("STATUS", "0");// 0:未同步|1:已同步|2:已注销|3:删除
				paraMap.put("COMPANYID", companywechatid);
				DBSql.update(insertUserSql, paraMap);
			}

		}
	}

	public void updateUserInfoAws(List<UserModel> users) {
		List<String> ext5AwsList = new ArrayList<String>();

		for (int i = 0; i < users.size(); i++) {

			UserModel user = users.get(i);

			String ext5Aws = user.getExt5();
			String uidAws = user.getUID();

			String depIdAws = user.getDepartmentId();
			String nameAws = user.getUserName();
			String mobile = user.getMobile();
			String queryUserInfoSql;

			if (!mobile.equals("")) {
				queryUserInfoSql = "select a.USERID,a.DEPID,a.USERNAME,a.MOBILE,a.STATUS,b.DEPIDAWS from WECHAT_USER a,BO_INFO_WECHAT_AWS b where a.DEPID=b.IDWECHAT AND a.USERNAME='"
						+ nameAws + "'";
			} else {
				queryUserInfoSql = "select a.USERID,a.DEPID,a.USERNAME,a.MOBILE,a.STATUS,b.DEPIDAWS from WECHAT_USER a,BO_INFO_WECHAT_AWS b where a.DEPID=b.IDWECHAT AND a.USERNAME='"
						+ nameAws + "'";
			}

			List<Map<String, Object>> userWechatList = DBSql.query(queryUserInfoSql, new ColumnMapRowMapper(),
					new Object[] {});
			if (userWechatList.size() == 0) {

				System.out.println("不存在用户:" + nameAws);
				if (!nameAws.contains("管理员")) {
					System.out.println("Aws Uid" + uidAws);
				}

			}
			if (!userWechatList.isEmpty() && userWechatList != null) {
				Map<String, Object> userWechat = userWechatList.get(0);
				String userIdWechat = CoreUtil.objToStr(userWechat.get("USERID"));
				String depIdWechat = CoreUtil.objToStr(userWechat.get("DEPID"));
				String userNameWechat = CoreUtil.objToStr(userWechat.get("USERNAME"));
				String MOBILE = CoreUtil.objToStr(userWechat.get("MOBILE"));
				

				String updateUserStatusSql = "UPDATE WECHAT_USER SET STATUS=1 WHERE USERID = '" + userIdWechat + "'";

				DBSql.update(updateUserStatusSql);

				if (!ext5AwsList.contains(userIdWechat)) {
					if (!ext5Aws.equals(userIdWechat)) {
						Map attrs = new HashMap<String, Object>();
						attrs.put("departmentId", depIdAws);
						attrs.put("mobile",MOBILE);
						attrs.put("ext5", userIdWechat);
						SDK.getORGAPI().updateUser(uidAws, attrs);
					}
					ext5AwsList.add(userIdWechat);
				} else {
					System.out.println("重复用户:" + nameAws);
					String updateUserDeleteStatusSql = "UPDATE WECHAT_USER SET STATUS=3 WHERE USERID = '" + userIdWechat
							+ "'";
					DBSql.update(updateUserDeleteStatusSql);
				}

			}

		}

	}

	public void mergerNewAccount(String role) {

		String queryUserInfoSql = "select a.USERID,a.DEPID,a.USERNAME,a.MOBILE,a.STATUS,b.DEPIDAWS from WECHAT_USER a,BO_INFO_WECHAT_AWS b where a.DEPID=b.IDWECHAT AND a.COMPANYID=b.CONMPANYIDWECHAT AND a.STATUS='0'";
		List<Map<String, Object>> userWechatList = DBSql.query(queryUserInfoSql, new ColumnMapRowMapper(),
				new Object[] {});
		System.out.println(userWechatList.size());
		for (int i = 0; i < userWechatList.size(); i++) {
			Map<String, Object> userWechat = userWechatList.get(i);
			String userIdWechat = CoreUtil.objToStr(userWechat.get("USERID"));
			String depIdWechat = CoreUtil.objToStr(userWechat.get("DEPID"));
			String userNameWechat = CoreUtil.objToStr(userWechat.get("USERNAME"));
			String MOBILE = CoreUtil.objToStr(userWechat.get("MOBILE"));
			String depIdAws = CoreUtil.objToStr(userWechat.get("DEPIDAWS"));
			System.out.println(userNameWechat);
			int c_re = SDK.getORGAPI().createUser(depIdAws, userIdWechat, userNameWechat, role, null, null, false, null,
					MOBILE, null, null, null, null, null, null, null, null, null, null, userIdWechat, null);
			String updateUserStatusSql = "UPDATE WECHAT_USER SET STATUS=1 WHERE USERID = '" + userIdWechat + "'";
			DBSql.update(updateUserStatusSql);
		}

	}

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		String cfgstr = readToString(
				"E:\\Actionsoft\\bpm808\\bpm804\\apps\\install\\com.awspaas.user.apps.shhtaerospaceindustrial\\lib\\company.json");
//String cfgstr = readToString("C:\\awsinst808test\\apps\\install\\com.awspaas.user.apps.shhtaerospaceindustrial\\lib\\company.json");		
		JSONArray companyArray = null;
		JSONObject jsonObject = JSONObject.fromObject(cfgstr);
		if (jsonObject != null) {
			// 取出按钮权限的数据
			companyArray = jsonObject.getJSONArray("companys");
		}
		Iterator<Object> num = companyArray.iterator();
		while (num.hasNext()) {
			JSONObject company = (JSONObject) num.next();
			String c_wechatid = (String) company.get("companywechatid");
			String c_secret = (String) company.get("companywechatseret");
			String c_awsid = (String) company.get("awsid");
			String role = (String) company.get("companyuserrole");
			WeChatUtil wechat = new WeChatUtil();

			String access_token = wechat.getAccessToken(c_wechatid, c_secret);
			List<Map<String, String>> depsWechat = wechat.getDepartmentList(access_token);
			List<WxUserInfo> wechatuserlist = wechat.getDepartmentUserDetails(depsWechat, access_token, "0");
			updateUserTable(wechatuserlist, c_wechatid);

			List<Department> depsAws = getAllDeps(c_awsid);
			UpdateDepartments(depsWechat, depsAws, c_awsid, c_wechatid);
			depsAws = getAllDeps(c_awsid);
			updateUserTable(wechatuserlist, c_wechatid);

			List<UserModel> users = getAllUserByDepartments(depsAws);
			updateUserInfoAws(users);
			mergerNewAccount(role);

		}
		System.out.println("完成同步！");
	}
}
